package com.xsz.pda.ui

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.nfc.NfcAdapter
import android.nfc.Tag
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.widget.EditText
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.beardedhen.androidbootstrap.BootstrapButton
import com.blankj.utilcode.util.ToastUtils
import com.eidlink.idocr.sdk.IDOCRCardType
import com.eidlink.idocr.sdk.bean.EidlinkResult
import com.eidlink.idocr.sdk.listener.OnGetResultListener
import com.xsz.pda.App
import com.xsz.pda.AppExecutors
import com.xsz.pda.Config
import com.xsz.pda.R
import com.xsz.pda.common.OnlineChecker
import com.xsz.pda.data.bean.TicketInfo
import com.xsz.pda.data.model.TicketModel
import com.xsz.pda.device.eid.MyNfcManager
import com.xsz.pda.device.eid.NfcListener
import com.xsz.pda.device.eid.ReadCardManager
import com.xsz.pda.event.EmqConn
import com.xsz.pda.event.ShowDownloadSize
import com.xsz.pda.utils.DateTimeUtil
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class MainActivity : AppCompatActivity(),MainContract.View, OnlineChecker {

    private lateinit var presenter: MainPresenter
    private lateinit var tvInfo1: TextView
    private lateinit var tvCheckCount: TextView
    private lateinit var tvCheckMsg: TextView
    private lateinit var tvDeviceName: TextView
    private lateinit var tvDeviceGroup: TextView
    private lateinit var tvDeviceProj: TextView
    private lateinit var tvNetStatus: TextView
    private lateinit var tvDataStatus: TextView
    private lateinit var tvInfo2: TextView
    private lateinit var tvInfo3: TextView
    private lateinit var tvCheckCountToday: TextView
    private lateinit var tvLastIn: TextView
    private val resetor = Resetor(3000)

    private var mNfcAdapter: NfcAdapter? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        App.openFirstCheck = Config.isOpenFirstCheck()
        initView()
        presenter = MainPresenter(this)
        presenter.init()
        if (TextUtils.isEmpty(Config.getName())) goSettings()
        App.checkIdCard = Config.isCheckIDCARD()
        if (App.checkIdCard) { ReadCardManager.initEid(this) }
    }


    override fun onResume() {
        super.onResume()
        presenter.onResume()

        if (App.checkIdCard) {
            mNfcAdapter = MyNfcManager.enableReaderMode(this, object : NfcListener {
                override fun onNfcEvent(tag: Tag?) {
                    if (ReadCardManager.eid == null) {
                        ToastUtils.showShort("eid对象为空，请初始化sdk成功后再使用sdk功能。")
                        return
                    }
                    //二代证读取
                    ReadCardManager.eid.readIDCard(
                        this@MainActivity,
                        IDOCRCardType.IDCARD,
                        tag,
                        object : OnGetResultListener() {
                            override fun onSuccess(result: EidlinkResult) {
                                val idNumber = result.getIdentity().getIdnum()
                                val name = result.getIdentity().getName()
                                AppExecutors.diskIO.execute {
                                    TicketModel.check(null, null, idNumber).apply {
                                        runOnUiThread {
                                            val root = layoutInflater.inflate(R.layout.dialog_showinfo, null)
                                            val showname = root.findViewById<TextView>(R.id.showname)
                                            val showidnumber = root.findViewById<TextView>(R.id.showidnumber)
                                            val showseat = root.findViewById<TextView>(R.id.showseat)
                                            val showToast = root.findViewById<TextView>(R.id.showToast)
                                            showname.text = "**${name.last()}"
                                            showidnumber.text = "${idNumber.slice(0..2)}****${idNumber.slice(idNumber.length-5..idNumber.length-1)}"
                                            if (first != null) {
                                                showseat.text = first!!.seat
                                                showToast.text = "验证成功"
                                                showToast.setTextColor(Color.GREEN)
                                            } else {
                                                showToast.text = second
                                                showToast.setTextColor(Color.RED)
                                            }
                                            val dialog = android.app.AlertDialog.Builder(this@MainActivity)
                                                .setView(root)
                                                .setTitle("验证结果")
                                                .setPositiveButton("关闭", null)
                                                .show()

                                            AppExecutors.mainThread.schedule({ dialog.dismiss() },3000)
                                        }

                                    }
                                }
                            }

                            @RequiresApi(Build.VERSION_CODES.M)
                            override fun onFailed(code: Int, msg: String, biz_id: String) {
                                Log.i("Main", "读卡失败: $code,$msg,biz_id$biz_id")
                                ToastUtils.showShort(msg)
                            }

                            @RequiresApi(Build.VERSION_CODES.M)
                            override fun onStart() {
                                super.onStart()
                                ToastUtils.showShort("开始读卡,请勿移动")
                            }
                        })
                    /**
                     * ReadCardManager.eid.readIDCard(tag, mResultListener);
                     * 通用模式，同时支持二代证读取和eID电子证照读取
                     */
//                    ReadCardManager.eid.readIDCard(
//                        this@MainActivity,
//                        tag,
//                        object : OnGetResultListener() {
//                            override fun onSuccess(result: EidlinkResult) {
//                                val idNumber = result.getIdentity().getIdnum()
//                                val name = result.getIdentity().getName()
//                                presenter.checkIdCard(idNumber, name)
//                                if (result.getIdentity() != null && !TextUtils.isEmpty(
//                                        result.getIdentity().getPicture()
//                                    )
//                                ) {
//    //                val bt = IDCardPhoto.getIDCardPhoto(result.getIdentity().getPicture())
//    //                if (bt != null) {
//    //                    iv_image.setVisibility(View.VISIBLE)
//    //                    iv_image.setImageBitmap(bt)
//    //                }
//                                }
//                            }
//
//                            @RequiresApi(Build.VERSION_CODES.M)
//                            override fun onFailed(code: Int, msg: String, biz_id: String) {
//                                Log.i("Main", "读卡失败: $code,$msg,biz_id$biz_id")
//                                showMsg(msg, 2)
//                                resetor.resetInfoDelay()
//                            }
//
//                            @RequiresApi(Build.VERSION_CODES.M)
//                            override fun onStart() {
//                                super.onStart()
//                                showMsg("开始读卡,请勿移动", 1)
//                                resetor.resetInfoDelay()
//                            }
//                        })
                    /**
                     * ReadCardManager.eid.readIDCard(IDOCRCardType.IDCARD,tag, mResultListener);
                     * 设置只支持二代证读取
                     */
            //        ReadCardManager.eid.readIDCard(IDOCRCardType.IDCARD,tag, mResultListener);
                            /**
                             * ReadCardManager.eid.readIDCard(IDOCRCardType.ECCARD,tag, mResultListener);
                             * 设置只支持eID电子证照读取
                             */
            //        ReadCardManager.eid.readIDCard(IDOCRCardType.ECCARD,tag, mResultListener);
                }

                override fun onNfcError(has: Boolean) {
                    if (has) {
                        ToastUtils.showLong("设备未开启NFC")
                    } else {
                        ToastUtils.showLong("设备不支持NFC")
                    }
                }
            })
        }
        setInfo()
    }


    override fun onPause() {
        super.onPause()
        if (App.checkIdCard) {
            MyNfcManager.disableReaderMode(this, mNfcAdapter)
        }
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        if (!App.checkIdCard) {
            intent?.let { presenter.parseNfc(it) }
        }

    }

    @SuppressLint("SetTextI18n")
    private fun initView(){
        tvInfo2 = findViewById(R.id.tvInfo2)
        tvInfo3 = findViewById(R.id.tvInfo3)
        tvCheckMsg = findViewById(R.id.tvCheckMsg)
        tvDeviceName = findViewById(R.id.tvDeviceName)
        tvDeviceGroup = findViewById(R.id.tvDeviceGroup)
        tvDeviceProj = findViewById(R.id.tvDeviceProj)
        tvInfo1=findViewById(R.id.tvTicketRfid)
        tvCheckCount = findViewById(R.id.tvCheckCount)
        tvNetStatus = findViewById(R.id.tvNetStatus)
        tvDataStatus = findViewById(R.id.tvDataStatus)
        tvCheckCountToday = findViewById(R.id.tvCheckCountToday)
        tvCheckCount = findViewById(R.id.tvCheckCount)
        tvLastIn = findViewById(R.id.lastIn)
        findViewById<BootstrapButton>(R.id.btnSave).setOnClickListener { goSettings() }
        findViewById<BootstrapButton>(R.id.btnSearch).setOnClickListener { goSearchView() }
        findViewById<BootstrapButton>(R.id.btnGoDel).setOnClickListener { goDelView() }
        setInfo()
        resetor.addOnResetListener {
            runOnUiThread{
                tvInfo1.text = "请刷票"
                tvLastIn.text = ""
                tvCheckMsg.text = ""
                tvInfo2.text = ""
                tvInfo3.text = ""
            }
        }
        showGroupName(Config.getGroupName())
    }


    private fun goSettings() {
//        val goSettings = Intent(this, SettingsActivity::class.java)
//        startActivity(goSettings)
        val root = layoutInflater.inflate(R.layout.dialog_validate, null)
        val edpwd = root.findViewById<EditText>(R.id.password)
        AlertDialog.Builder(this)
            .setView(root)
            .setTitle("身份验证")
            .setPositiveButton("确认") { d, _ ->
                if (edpwd.text.toString() == "0425") {
                    val goSettings = Intent(this, SettingsActivity::class.java)
                    startActivity(goSettings)
                    d.dismiss()
                } else {
                    ToastUtils.showShort("密码错误")
                }
            }
            .setNegativeButton("取消", null)
            .show()

    }


    @SuppressLint("SetTextI18n")
    private fun setInfo() {
        tvDeviceProj.text = "项目号：" + Config.getProjectNo()
        tvDeviceName.text = "名称：" + Config.getName()
        tvInfo1.text = "请刷票证"
    }

    override fun showTicketType(type: String) {}

    @RequiresApi(Build.VERSION_CODES.M)
    override fun showMsg(msg: String, type: Int) {
        runOnUiThread {
            tvCheckMsg.setTextColor(
                if (type==1) getColor(R.color.bootstrap_brand_success)
                else getColor(R.color.bootstrap_brand_danger))
            tvCheckMsg.text = msg
        }
    }


    @SuppressLint("SetTextI18n")
    override fun showCheckCount(todayCount: String, allCount: String) {
       runOnUiThread {
           tvCheckCountToday.text = "今日验票： $todayCount"
           tvCheckCount.text = "总验票： $allCount"
       }
    }

    @RequiresApi(Build.VERSION_CODES.M)
    override fun showTicket(ticket: TicketInfo, lastInTime: String, lastInGroup: String, msg: String, type: Int) {
        runOnUiThread {
            if (type == 1) {
                tvLastIn.text = if (!TextUtils.isEmpty(lastInTime)) {
                    "${DateTimeUtil.getShortTime(lastInTime)},在${lastInGroup}进入"
                } else {
                    "首次通过"
                }
            }
            tvInfo1.text = ticket.name
            if(!TextUtils.isEmpty(ticket.idNumber)){
                tvInfo2.text = ticket.idNumber
            }
            if (!TextUtils.isEmpty(ticket.seat)) {
                tvInfo3.text = ticket.seat
            }
            tvCheckMsg.setTextColor(
                if (type==1) getColor(R.color.bootstrap_brand_success)
                else getColor(R.color.bootstrap_brand_danger))
            tvCheckMsg.text = msg
        }
        resetor.resetInfoDelay()
    }

    override fun showGroupName(groupName: String) {
       runOnUiThread{ tvDeviceGroup.text = groupName}
    }


    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun showDownloadSize(size: ShowDownloadSize) {
        tvDataStatus.text = "${size.local}/${size.all}"
    }

    @RequiresApi(Build.VERSION_CODES.M)
    override fun showNetStatus(event: EmqConn) {
        runOnUiThread {
            if(event.isOnline){
                tvNetStatus.text = "在线"
                tvNetStatus.setTextColor(getColor(R.color.bootstrap_brand_success))
            }else{
                tvNetStatus.text = "离线"
                tvNetStatus.setTextColor(getColor(R.color.bootstrap_brand_warning))
            }
        }
    }

    override fun onStart() {
        super.onStart()
        EventBus.getDefault().register(this)
    }

    override fun onStop() {
        EventBus.getDefault().unregister(this)
        super.onStop()
    }

    override fun onDestroy() {
        presenter.release()
        super.onDestroy()
    }

    override fun isOnline(): Boolean {
        return true
    }

    override fun onBackPressed() {
        AlertDialog.Builder(this).setTitle("确定退出？")
            .setPositiveButton("确定") { d, _ ->
                d.dismiss()
                super.onBackPressed()
            }
            .setNegativeButton("取消", null)
            .show()
    }
    private fun goSearchView(){
        val goSearch = Intent(this, SearchActivity::class.java)
        startActivity(goSearch)
    }

    private fun goDelView(){
        val goDelView = Intent(this, DeleteFaceActivity::class.java)
        startActivity(goDelView)
    }
}